package com.itheima.service.impl;


import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetMealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetMealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetMealService.class)
@Transactional
public class SetMealServiceImpl implements SetMealService {

    //使用JedisPool操作redis
    @Autowired
    private JedisPool jedisPool;

    //注入checkItemDao对象
    @Autowired
    private SetMealDao setMealDao;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outPutPath;//从属性文件中读取要生成的html对应的目录

    /**
     * 添加套餐功能
     *
     * @param setmeal
     * @param checkgroupIds
     */
    @Override
    public void add(@RequestBody Setmeal setmeal, Integer[] checkgroupIds) {
        //添加Setmeal对象,操作t_setmeal表
        setMealDao.add(setmeal);
        //关联检查组对象,操作关联表
        Integer setmealId = setmeal.getId();
        //调用方法
        this.setSetmealAndCheckgroup(setmealId, checkgroupIds);
        //将存入数据库的图片名存入到redis中
        String fileName = setmeal.getImg();
        Jedis jedis = jedisPool.getResource();
        jedis.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, fileName);
        //归还池连接
        jedis.close();

        //当添加套餐后需要重新生成静态页面（套餐列表页面、套餐详情页面）
        generateMobileStaticHtml();
    }

    //套餐分页查询功能
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //分页助手
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> page = setMealDao.findByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    //获取所有的套餐信息
    @Override
    public List<Setmeal> getAllSetMeal() {
        return setMealDao.getAllSetMeal();
    }

    @Override
    public Setmeal findById(int id) {
        return setMealDao.findById(id);
    }

    @Override
    public List<Integer> findCheckGroupIdsBySetMealId(int id) {
        return setMealDao.findCheckGroupIdsBySetMealId(id);
    }

    @Override
    public void delete(int id) {
        //删除t_setMeal_checkGroup关系表中的数据
        setMealDao.delAssociation(id);
        //删除t_setMeal套餐表中的数据
        setMealDao.delete(id);
    }

    /**
     * 查询套餐名称以及预约数量
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setMealDao.findSetmealCount();
    }

    /**
     * 获取套餐收入信息
     *
     * @return
     * @param beginDate
     * @param endDate
     */
    @Override
    public Map<String, Object> getSetMealIncome(String beginDate, String endDate) {

        //获取所有套餐名称
        List<String> setMealNames = setMealDao.getAllSetMealNames();

        List<Map<String,Object>> setMeal = new ArrayList<>();

        Map<String,Object> data = new HashMap<>();

        for (String setMealName : setMealNames) {
            Map<String,Object> map = setMealDao.getSetMealIncome(beginDate,endDate,setMealName);
            Long count = (Long) map.get("count");
            Float price = (Float) map.get("price");
            String name = (String) map.get("name");
            Map<String,Object> m = new HashMap<>();
            if (count == 0 ){
                m.put("value",0);
                m.put("name",setMealName);
                setMeal.add(m);
            }else {
                m.put("value",(price * count));
                m.put("name",setMealName);
                setMeal.add(m);
            }
        }
        data.put("setMealName",setMealNames);
        data.put("setMeal",setMeal);
        return data;
    }

    //提取方法,关联套餐与检查组的关系
    public void setSetmealAndCheckgroup(Integer setmealId, Integer[] checkgroupIds) {

        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("setmealId", setmealId);
                map.put("checkgroupId", checkgroupId);
                setMealDao.setCheckGroupAndCheckItem(map);
            }
        }
    }

    //生成当前方法所需的静态页面
    public void generateMobileStaticHtml() {
        //在生成静态页面之前需要查询数据
        List<Setmeal> list = setMealDao.getAllSetMeal();

        //需要生成套餐列表静态页面
        generateMobileSetmealListHtml(list);

        //需要生成套餐详情静态页面
        generateMobileSetmealDetailHtml(list);
    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> list) {
        Map map = new HashMap();
        //为模板提供数据，用于生成静态页面
        map.put("setmealList", list);
        generteHtml("mobile_setmeal.ftl", "m_setmeal.html", map);
    }

    //生成套餐详情静态页面（可能有多个）
    public void generateMobileSetmealDetailHtml(List<Setmeal> list) {
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal", setMealDao.findById(setmeal.getId()));
            generteHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", map);
        }
    }

    //通用的方法，用于生成静态页面
    public void generteHtml(String templateName, String htmlPageName, Map map) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();//获得配置对象
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            out = new FileWriter(new File(outPutPath + "/" + htmlPageName));
            //输出文件
            template.process(map, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                //关闭流
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
